function urlEncode(param, key, encode) {
  if(param==null) return '';
  var paramStr = '';
  var t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};


const defaultOptions = {
  credentials: 'include', //设置该属性可以把 cookie 信息传到后台
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  }
};


const callApiFn =  (url = '',body = {},method = 'get') => {

  const options = {
    method,
    ...defaultOptions,
    body
  };

  return fetch(url,options)
    .then(response=>response.json())
    .then(data=>{
      return data;
    }).catch(error=>{
      console.error(error,'error-----');
    });
}

export const callApi = {
  get : function (url = '',body = {}) {
    var params = urlEncode(body);
    url = url.indexOf('?') > 0 ? url+params : url+'?'+params;
    return callApiFn(url,{},'get')
  },
  post : function (url = '',body = {}) {
    return callApiFn(url,body,'post')
  }
}

